package com.stf.rocketmq.controller;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 异步消息发送
 * @author shangtf
 *
 * */
@RestController
@RequestMapping("/asyncMq")
@Slf4j
public class AsyncProducerController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate; //注入Mq


    /**
     * 异步消息发送同理 同步消息 参考方法：
     *
     * //发送普通异步消息-Object
     * asyncSend(String destination, Object payload, SendCallback sendCallback)
     * //发送普通异步消息-Message
     * asyncSend(String destination, Message<?> message, SendCallback sendCallback)
     * //发送普通异步消息-Object，并设置发送超时时间
     * asyncSend(String destination, Object payload, SendCallback sendCallback, long timeout)
     * //发送普通异步消息-Message，并设置发送超时时间
     * asyncSend(String destination, Message<?> message, SendCallback sendCallback, long timeout)
     * //发送普通异步延迟消息，并设置超时，这个下文会演示
     * asyncSend(String destination, Message<?> message, SendCallback sendCallback, long timeout, int delayLevel)
     *
     * */


    //发送普通异步消息-Object
    @GetMapping("/sendMqAsync1")
    public Object sendMqAsync() {
        rocketMQTemplate.asyncSend("async_topic_string", "rocketmg异步消息！", new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送成功:{}", JSON.toJSONString(sendResult));
                //可以处理相应的业务
            }

            @Override
            public void onException(Throwable throwable) {
                //可以处理相应的业务
                log.info("发送失败:{}", JSON.toJSONString(throwable.getMessage()));
            }
        });

        return null;
    }



    /**
     * 异步延迟消息
     */
    @GetMapping("/sendMqAsync2")
    public void asyncSendDelayedStr() {

        //Callback
        SendCallback sc=new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送异步延时消息成功");
            }
            @Override
            public void onException(Throwable throwable) {
                log.info("发送异步延时消息失败:{}",throwable.getMessage());
            }
        };
        Message<String> message= MessageBuilder.withPayload("asyncSendDelayedStr").build();
        rocketMQTemplate.asyncSend("first-topic-str:tag1", message, sc, 3000, 3);

    }

}
